package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"net/http"
	"runtime"
	"time"
)

var MySqlDB *sql.DB

func main() {
	var err error
	runtime.GOMAXPROCS(runtime.NumCPU())
	MySqlDB, err = sql.Open("mysql", "dba_user:dba_user_!@#@tcp(10.9.98.136:3306)/seven?charset=utf8")
	fmt.Println(err)
	err = MySqlDB.Ping()
	if err != nil {
		fmt.Println(err.Error())
	}
	MySqlDB.SetMaxOpenConns(2000)
	MySqlDB.SetMaxIdleConns(2000)
	MySqlDB.SetConnMaxLifetime(3595 * time.Second)
	http.HandleFunc("/single", user)
	http.HandleFunc("/multi", userskill)
	fmt.Println("start")
	err = http.ListenAndServe(":5102", nil)
	if err != nil {
		fmt.Println("start error:", err)
	}
}

func user(w http.ResponseWriter, r *http.Request) {
	result := getAllUser()
	resultS, err := json.Marshal(result)
	if err != nil {
		panic(err)
	}
	fmt.Fprintln(w, string(resultS))
	return
}

func getAllUser() (result []map[string]interface{}) {
	rows, err := MySqlDB.Query("SELECT id,name,sex FROM user")
	if err != nil {
		fmt.Println(err)
		panic(err)
	}

	var id sql.NullInt64
	var name sql.NullString
	var sex sql.NullInt64
	defer rows.Close()
	for rows.Next() {
		// var wrongtopicIds string
		result_tmp := make(map[string]interface{})
		err := rows.Scan(&id, &name, &sex)
		if err != nil {
			panic(err)
		}
		result_tmp["ID"] = id.Int64
		result_tmp["NAME"] = name.String
		result_tmp["SEX"] = sex.Int64
		result = append(result, result_tmp)
	}

	return
}

func getAllSkill() (result []map[string]interface{}) {
	rows, err := MySqlDB.Query("SELECT id,userid,skill FROM skill")
	if err != nil {
		panic(err)
	}
	var id sql.NullInt64
	var userid sql.NullInt64
	var skill sql.NullString
	defer rows.Close()
	for rows.Next() {
		result_tmp := make(map[string]interface{})
		err := rows.Scan(&id, &userid, &skill)
		if err != nil {
			panic(err)
		}
		result_tmp["ID"] = id.Int64
		result_tmp["SKILL"] = skill.String
		result_tmp["USERID"] = userid.Int64
		result = append(result, result_tmp)
	}
	return
}

func userskill(w http.ResponseWriter, r *http.Request) {
	result1 := getAllUser()

	result2 := getAllSkill()

	result := make(map[string][]interface{})

	for _, v := range result1 {
		// result[""]
		key := v["NAME"].(string)
		if _, ok := result[key]; !ok {
			result[key] = make([]interface{}, 0, 0)
		}

		for _, vv := range result2 {
			if v["ID"] == vv["USERID"] {
				result[key] = append(result[key], vv["SKILL"])
			}
		}
	}
	resultS, err := json.Marshal(result)
	if err != nil {
		panic(err)
	}
	fmt.Fprintln(w, string(resultS))
	return
}
